package com.xlh.util;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 该类的作用可以把方法上的参数绑定到注解的变量中,注解的语法#{变量名}
 * 能解析类似#{task}或者#{task.taskName}或者{task.project.projectName}
 *
 * @author cheer
 */
public class AnnotationResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(AnnotationResolver.class);

    /**
     * 解析注解上的值
     *
     * @param joinPoint 切入点
     * @param str       需要解析的字符串
     * @return 解析后的注解值
     */
    public static String resolver(JoinPoint joinPoint, String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }

        Pattern pattern = Pattern.compile("#\\{.+?}");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            String resolvedStr = matcher.group().replaceAll("#\\{", "").replaceAll("}", "");
            String replacedStr = "";
            if (resolvedStr.contains(".")) { // 复杂类型
                try {
                    replacedStr = complexResolver(joinPoint, resolvedStr);
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }
            } else {
                replacedStr = simpleResolver(joinPoint, resolvedStr);
            }
            str = str.substring(0, matcher.start()) + replacedStr + str.substring(matcher.end());
            matcher = pattern.matcher(str);
        }

        return str;
    }

    private static String complexResolver(JoinPoint joinPoint, String str) throws Exception {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        String[] names = methodSignature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        String[] strings = str.split("\\.");

        for (int i = 0; i < names.length; i++) {
            if (strings[0].equals(names[i])) {
                Object obj = args[i];
                Method method = obj.getClass().getDeclaredMethod(getMethodName(strings[1]));
                Object value = method.invoke(args[i]);
                return getValue(value, 1, strings);
            }
        }

        return "";
    }

    private static String getValue(Object obj, int index, String[] strings) {
        try {
            if (obj != null && index < strings.length - 1) {
                Method method = obj.getClass().getDeclaredMethod(getMethodName(strings[index + 1]));
                obj = method.invoke(obj);
                getValue(obj, index + 1, strings);
            }
            return String.valueOf(obj);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return "";
    }

    private static String getMethodName(String name) {
        return "get" + name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
    }

    private static String simpleResolver(JoinPoint joinPoint, String str) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] names = methodSignature.getParameterNames();
        Object[] args = joinPoint.getArgs();

        for (int i = 0; i < names.length; i++) {
            if (str.equals(names[i])) {
                return args[i].toString();
            }
        }
        return "";
    }
}